package com.example.wan1.view.system.question;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;

import com.example.wan1.R;
import com.example.wan1.adapter.ArticleListAdapter;
import com.example.wan1.base.fragment.SimpleFragment;
import com.example.wan1.bus.RxBus;
import com.example.wan1.constant.Constants;
import com.example.wan1.event.CollectEvent;
import com.example.wan1.model.ArticleBean;
import com.example.wan1.model.common.CommonResList;
import com.example.wan1.utils.AppUtils;
import com.example.wan1.utils.ToastUtils;
import com.example.wan1.view.collect.HandleCollectTool;
import com.example.wan1.view.login.UserManager;
import com.example.wan1.view.web.JumpTool;
import com.scwang.smart.refresh.header.MaterialHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;

/***
 * 创建时间：2020/7/8 21:47
 * 创建人：10850
 * 功能描述：
 */
public class QuestionFragment extends SimpleFragment implements QuestionContract.View, OnLoadMoreListener, OnRefreshListener {

    @BindView(R.id.srlheader)
    MaterialHeader mSrlheader;
    @BindView(R.id.article_rv)
    RecyclerView mArticleRv;
    @BindView(R.id.srl)
    SmartRefreshLayout mSrl;
    @Inject
    QuestionPresenter mPresenter;
    @Inject
    ArticleListAdapter mAdapter;
    @Inject
    List<ArticleBean> mArticleList;//文章列表
    private int curPage = 1;//当前页

    @Override
    protected void initData() {
        mPresenter.getQuestionList(curPage);
    }

    @Override
    protected void initView() {
        showLoading();
        //mSrlheader.setColorSchemeResources(R.color.qc_green);
        mArticleList = new ArrayList<>();

        mAdapter = new ArticleListAdapter(R.layout.article_item, mArticleList);
        mArticleRv.setAdapter(mAdapter);
        mArticleRv.setLayoutManager(new LinearLayoutManager(mContext));

        mSrl.setOnLoadMoreListener(this);
        mSrl.setOnRefreshListener(this);

        mSrl.setEnableRefresh(false);
        mSrl.setEnableLoadMore(false);

        mAdapter.setOnItemClickListener((baseQuickAdapter, view, i) -> {
            JumpTool.goWeb(mContext, mArticleList.get(i).getTitle(), mArticleList.get(i).getLink());
            HandleCollectTool.getInstance().setInfo(mArticleList.get(i), i, Constants.ARTICLE);
        });

        mAdapter.setOnItemChildClickListener((baseQuickAdapter, view12, i) -> {
            switch (view12.getId()) {
                case R.id.article_iv_collect: {
                    if (!UserManager.getInstance().isLogin()){
//                    if (!AppUtils.isLogin()) {
                        JumpTool.goLogin(getActivity());
                        return;
                    }
                    ArticleBean articleBean = mArticleList.get(i);
                    HandleCollectTool.getInstance().setInfo(articleBean, i, Constants.ARTICLE);
                    ImageView iv = view12.findViewById(R.id.article_iv_collect);
                    if (articleBean.isCollect()) {
                        HandleCollectTool.getInstance().cancelList();
                        iv.setImageResource(R.mipmap.heart_gray);
                    } else {
                        HandleCollectTool.getInstance().collectIn();
                        iv.setImageResource(R.mipmap.heart_red);
                    }
                }
                break;
            }
        });
        mArticleRv.addOnScrollListener(mOnScrollListener);
    }

    @Override
    protected int initLayoutRes() {
        return R.layout.fragment_article;
    }

    @Override
    public void onSuccess(CommonResList<ArticleBean> data) {
        hideLoading();
        if (data.isOver()) {
            mAdapter.loadMoreEnd();
            if (mAdapter.getFooterLayoutCount() == 0) {
                View footer = LayoutInflater.from(mContext).inflate(R.layout.loadmore_view, null);
                mAdapter.addFooterView(footer);
            }
            mSrl.setEnableLoadMore(false);
        }
        if (data.getDatas().size() == 0) return;
        mSrl.setEnableRefresh(true);
        mSrl.setEnableLoadMore(true);
        curPage = data.getCurPage() + 1;
        mAdapter.addData(data.getDatas());
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onFailure(String msg) {
        showError();
        mSrl.setEnableLoadMore(false);
        mSrl.setEnableRefresh(false);
        ToastUtils.showToast(msg);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        mArticleRv.postDelayed(() -> {
            mPresenter.getQuestionList(curPage);
            mSrl.finishLoadMore(true);
        }, 200);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mArticleRv.postDelayed(() -> {
            mPresenter.getQuestionList(1);
            mSrl.finishRefresh(true);
        }, 200);
    }

    public void notifyItemCollect() {
        if (mArticleRv.getAdapter() == null)
            mAdapter.bindToRecyclerView(mArticleRv);
        int pos = HandleCollectTool.getInstance().getPosition();
        mAdapter.notifyItemChanged(pos);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        RxBus.getDefault().subscribeSticky(mContext, new RxBus.Callback<CollectEvent>() {
            @Override
            public void onEvent(CollectEvent collectEvent) {
                if (Constants.ARTICLE.equals(collectEvent.getType()))
                    notifyItemCollect();
            }
        });
        RxBus.getDefault().subscribe(mContext, new RxBus.Callback<String>() {
            @Override
            public void onEvent(String s) {
                if (s.equals("cancelArticle")) {
                    mArticleList.clear();
                    mPresenter.getQuestionList(1);
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unregister(mContext);
    }
}